package com.work.account2.service;

import com.work.account2.entity.Account;
import com.work.account2.repository.AccountDAO;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

/**
 * @author YonJar
 * @date 2024/6/12.
 * @description
 */
@Slf4j
@Service
public class TccAccountServiceImpl implements TccAccountService {

    @Resource
    private AccountDAO accountDAO;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext context, String userId, BigDecimal orderMoney) {
        //校验是否存在
        Account account = accountDAO.findByUserId(userId);
        if (Objects.isNull(account)){
            return false;
        }

        log.info("########### 打印，XID = " + context.getXid());
        log.info("################ account prepare ################ ");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext context) {
        Map<String, Object> actionContext = context.getActionContext();
        String userId= (String) actionContext.get("userId");
        Integer orderMoney = (Integer) actionContext.get("orderMoney");
        BigDecimal bigDecimal = new BigDecimal(orderMoney);

        Account account = accountDAO.findByUserId(userId);
        account.setMoney(account.getMoney().subtract(bigDecimal));
        accountDAO.updateById(account);

        log.info("################ account commit ################ ");
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext context) {
        Map<String, Object> actionContext = context.getActionContext();
        String userId= (String) actionContext.get("userId");
        Integer orderMoney = (Integer) actionContext.get("orderMoney");
        BigDecimal bigDecimal = new BigDecimal(orderMoney);

        Account account = accountDAO.findByUserId(userId);
        account.setMoney(account.getMoney().add(bigDecimal));
        accountDAO.updateById(account);

        log.info("########### 打印，XID = " + context.getXid());
        log.info("################ account rollback ################");
        return true;
    }
}
